<?php

namespace App\Modules\Admin\Http\Controllers;

use App\Models\Config;
use App\Models\ConfigType;
use App\Modules\Admin\Http\Controllers\BaseController;
use App\Modules\Admin\Http\Requests\ConfigCreateRequest;
use App\Modules\Admin\Http\Requests\ConfigUpdateRequest;
use App\Modules\Admin\Http\Requests\ConfigTypeCreateRequest;
use Illuminate\Support\Facades\Cache;
use App\Services\Admin\ConfigService;
use Illuminate\Http\Request;


class ConfigController extends BaseController
{
    /**
     * 配置首页
     * @param Request $request
     * @method index
     * @author chengzhigang<1256699215@qq.com>
     */
    public function index(Request $request)
    {
        $id = $request->input('id',0);
        $data = ConfigType::with('children')->get();
        foreach($data as $k=>$val){
            foreach($val['children'] as $key=>$v){
                if($v['value_type']=='radio'||$v['value_type']=='checkbox'||$v['value_type']=='select'){
                    $v['options'] = json_decode($v['options']);
                }
                if($v['value_type']=='images'){
                    $v['value'] = explode(',',$v['value']);
                }
                $val['children'][$key] = $v;
            }
            $data[$k] = $val;
        }
        return view('admin::config/index',compact('data','id'));
    }

    /**
     * 添加配置页
     * @method create
     * @author chengzhigang<1256699215@qq.com>
     */
    public function create(){
        $types = ConfigType::orderBy('sort','desc')->get();
        return view('admin::config/create',compact('types'));
    }

    /**
     * 新增配置
     * @method store
     * @author chengzhigang<1256699215@qq.com>
     */
    public function store(ConfigCreateRequest $request){
        $data = $request->all();
        $dir = "uploads/config";
        if($data['value_type']=='image'){
            $image = $request->file('image');
            if($image){
                $result = upload($image,'image',['dir'=>$dir]);
                if($result['status']==2){
                    return apiResponse($result['msg']);
                }
                $data['value'] = $result['data'];
            }
        }
        if($data['value_type']=='images'){
            $images = $request->file('images');
            if($images){
                $result = uploads($images,'image',['dir'=>$dir]);
                if($result['status']==2){
                    return apiResponse($result['msg']);
                }
                $data['value'] = implode(',',$result['data']);
            }
        }
        //处理配置项
        if($data['value_type']=='radio'||$data['value_type']=='select'||$data['value_type']=='checkbox'){
            $data['options'] = explode("\n",$data['options']);
            $optionData = [];
            foreach($data['options'] as $val){
                $option = [];
                $optionArr = explode(':',$val);
                if(isset($optionArr[0])&&isset($optionArr[1])){
                    $option['key'] = $optionArr[0];
                    $option['value'] = $optionArr[1];
                    $optionData[] = $option;
                }
            }
            $data['options'] = json_encode($optionData);
        }
        //处理配置值
        if($data['value']){
            $data['value'] = str_replace("，", ",", trim($data['value']));
        }
        if(Config::create($data)){
            Config::setConfig($data['name'],$data['value']);
            return apiResponse('添加成功',1,[]);
        }else{
            return apiResponse('添加失败');
        }
    }
    //图片删除
    public function delImage(Request $request){
        $data = $request -> all();
        $name = $data['name'];
        $path = $data['path'];
        $config = Config::where('name',$name)->select('value','value_type')->first();
        if(empty($config)){
            return apiResponse('配置项不存在');
        }
        if($config->value_type=='image'){
            //单图
            $configValue = '';
        }elseif($config->value_type=='images'){
            //多图
            $value = explode(',',$config->value);
            foreach($value as $k => $v){
                if($v==$path){
                    unset($value[$k]);
                }
            }
            $configValue = implode(',',array_values($value));
        }
        Config::where('name',$name)->update(['value'=>$configValue]);
        Config::setConfig($name,$configValue);
        return apiResponse('删除成功',1,[]);
    }

    /**
     * 新增配置类型
     * @method typeStore
     * @author chengzhigang<1256699215@qq.com>
     * @param
     * @return
     */
    public function typeStore(ConfigTypeCreateRequest $request){
        $data = $request -> all();
        if(ConfigType::create($data)){
            return apiResponse('添加成功',1,[]);
        }else{
            return apiResponse('添加失败');
        }
    }

    /**
     * 修改配置
     * @param Request $request
     * @method update
     * @author chengzhigang<1256699215@qq.com>
     */
    public function update(Request $request){
        $data = $request->all();
        $file = $request->file();
        if($file){
            $dir = "uploads/config";
            foreach($file as $k=>$val){
                if(is_array($val)){
                   $result = uploads($val,'image',['dir'=>$dir]);
                   if($result['status']==2){
                       return apiResponse($result['msg']);
                   }
                   $config = Config::where('name',$k)->select('value')->first();
                   $valueArr = array_merge(explode(',',$config->value),$result['data']);
                   $data[$k] = implode(',',$valueArr);
                }else{
                    $result = upload($val,'image',['dir'=>$dir]);
                    if($result['status']==2){
                        return apiResponse($result['msg']);
                    }
                    $data[$k] = $result['data'];
                }
            }
        }
        unset($data['_token']);
        foreach($data as $k => $val){
            if(is_string($val)){
                Config::where('name',$k)->update(['value'=>$val]);
                Config::setConfig($k,$val);
            }
        }
        return apiResponse('修改成功',1,[]);
    }

    /**
     * 配置列表页
     * @param Request $request
     * @method list
     * @author chengzhigang<1256699215@qq.com>
     */
    public function list(Request $request){
        $param = $this->getParam('Config','Config/getList');
        return view('admin::config/list',compact('param'));
    }

    public function getList(Request $request){
        Cache::forever('Config/getList', $request->server->get('QUERY_STRING'));
        $page = $request->input('page', 1);
        $per_page = $request->input('limit', 10);
        $configService = new ConfigService();
        $result = $configService->getList($page,$per_page);
        if($result['status']==1){
            return layTableApi($result['data']['total'],$result['data']['data']);
        }else{
            return layTableApi(0,[],1);
        }
    }

    public function editSort(Request $request){
        $name = $request->input('name');
        $value = $request->input('value');
        Config::where('name',$name)->update(['sort'=>$value]);
        return apiResponse('修改成功',1,[]);
    }

    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)) {
            return apiResponse('请选择删除项');
        }
        if (Config::destroy($ids)) {
            return apiResponse('删除成功！',1,[]);
        }
        return apiResponse('删除失败！');
    }

    public function edit($id)
    {
        $config = Config::findOrFail($id);
        if($config->value_type=='radio'||$config->value_type=='checkbox'||$config->value_type=='select'){
            $config->options = json_decode($config->options,true);
            $configBox = [];
            foreach($config->options as $v){
                $options = $v['key'].':'.$v['value'];
                $configBox[] = $options;
            }
            $config->options = implode("\n",$configBox);
        }
        if($config->value_type=='images'){
            $config->value = explode(',',$config->value);
        }
        $types = ConfigType::orderBy('sort','desc')->get();
        return view('admin::config.edit', compact('config','types'));
    }

    public function editData(ConfigUpdateRequest $request){
        $data = $request->all();
        $dir = "uploads/config";
        Cache::forever('Config', true);
        if($data['value_type']=='image'){
            $image = $request->file('image');
            if($image){
                $result = upload($image,'image',['dir'=>$dir]);
                if($result['status']==2){
                    return apiResponse($result['msg']);
                }
                $data['value'] = $result['data'];
            }
            unset($data['image']);
        }
        if($data['value_type']=='images'){
            foreach ($data['images'] as $k=>$val) {
                if(!is_string($val)){
                    $result = upload($val,'image',['dir'=>$dir]);
                    if($result['status']==2){
                        return apiResponse($result['msg']);
                    }
                    $data['images'][$k] = $result['data'];
                }
            }
            ksort($data['images']);
            $data['value'] = implode(',', array_values($data['images']));
            unset($data['images']);
        }
        //处理配置项
        if($data['value_type']=='radio'||$data['value_type']=='select'||$data['value_type']=='checkbox'){
            $data['options'] = explode("\n",$data['options']);
            $optionData = [];
            foreach($data['options'] as $val){
                $option = [];
                $optionArr = explode(':',$val);
                if(isset($optionArr[0])&&isset($optionArr[1])){
                    $option['key'] = $optionArr[0];
                    $option['value'] = $optionArr[1];
                    $optionData[] = $option;
                }
            }
            $data['options'] = json_encode($optionData);
        }
        //处理配置值
        if($data['value']){
            $data['value'] = str_replace("，", ",", trim($data['value']));
        }
        if(Config::where('id',$data['id'])->update($data)){
            Config::setConfig($data['name'],$data['value']);
            return apiResponse('修改成功',1,[]);
        }else{
            return apiResponse('修改失败');
        }
    }


}
